package models

import (
	"github.com/astaxie/beego/orm"
	"errors"
	"mailsrv/utils"
	"github.com/astaxie/beego"
)

type Apps struct {
	Id              int `json:"id"`
	Mid				int `json:"mid"`
	Name 			string `json:"name"`
	Appid           string `json:"appid"`
	Appkey          string `json:"appkey"`
	Desc            string `json:"desc"`
	BaseTable
}

func (a *Apps) TableName() string {
	return TableMap["apps"]
}

//获取分页数据
func (apps *Apps) PageList(pagenum int) ([]*Apps, int64) {
	pagesize, _ := beego.AppConfig.Int("PageSize")
	query := orm.NewOrm().QueryTable(apps.TableName())
	data := make([]*Apps, 0)
	limit := (pagenum-1)*pagesize
	total, _ := query.Count()
	query.OrderBy("-Id").Limit(pagesize, limit).All(&data)
	return data, total
}

//获取所有all
func (apps *Apps) AllApps() ([]*Apps, int64) {
	query := orm.NewOrm().QueryTable(apps.TableName())
	data := make([]*Apps, 0)
	total, _ := query.Count()
	query.OrderBy("-Id").Limit(9999 ).All(&data)
	return data, total
}


//通过ID获取记录
func (apps *Apps) GetOne(id int)  (*Apps, error){
	o := orm.NewOrm()
	where := Apps{}
	qs := o.QueryTable(where.TableName())
	err := qs.Filter("id", id).One(&where)

	if err != nil {
		return nil, err
	}
	return &where, nil
}

//通过APPID获取记录
func (apps *Apps) GetOneByAppid(appid string) (*Apps, error){
	o := orm.NewOrm()
	where := Apps{}
	qs := o.QueryTable(where.TableName())
	err := qs.Filter("appid", appid).One(&where)

	if err != nil {
		return nil, err
	}
	return &where, nil
}

//通过APPID获取记录
func (apps *Apps) GetOneByMid(mid int64) (*Apps, error){
	o := orm.NewOrm()
	where := Apps{}
	qs := o.QueryTable(where.TableName())
	err := qs.Filter("mid", mid).One(&where)

	if err != nil {
		return nil, err
	}
	return &where, nil
}



//添加项目
func (apps *Apps) AppsInsert() error {
	o := orm.NewOrm()
	apps.BaseTable.Created_at = utils.GetNowTime()
	apps.BaseTable.Updated_at = utils.GetNowTime()

	info, _ := apps.GetOneByAppid(apps.Appid)

	if info != nil {
		return errors.New("appid已经存在了！")
	}

	// 插入数据
	_, err := o.Insert(apps)
	if err != nil {
		return err
	}
	return nil
}

//编辑项目
func (apps *Apps) AppsEdit() (int64, error) {
	o := orm.NewOrm()
	apps.BaseTable.Updated_at = utils.GetNowTime()

	if num, err := o.Update(apps, "Id","Mid", "Name", "Appid","Appkey", "Desc", "Updated_at"); err == nil {
		return num, err
	}else{
		return 0, err
	}
}

//删除机器
func (apps *Apps) AppsDel(id int)(int64, error){
	o := orm.NewOrm()
	apps.Id = id
	if num, err := o.Delete(apps); err == nil {
		return num, err
	}else{
		return 0, err
	}
}